/********************************************
 * 功能说明: RoleAuthority实体与DTO之间接口数据转换实现
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.web.converter;

import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.web.dto.WebRoleAuthorityDTO;
import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.model.RoleAuthority;
import com.spring.arch.uaa.repository.RoleAuthorityRepository;
import com.spring.arch.uaa.web.dto.WebRoleAuthorityDTO;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.spring.arch.uaa.errorcode.UaaErrorCode.E2001005002;

/**
 * RoleAuthority实体与DTO之间接口数据转换实现
 *
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Component
public class WebRoleAuthorityConverter extends AbstractConverter<RoleAuthority, WebRoleAuthorityDTO> {

    @Autowired
    private RoleAuthorityRepository roleAuthorityRepository;

    @Override
    public RoleAuthority toModel(@NonNull final WebRoleAuthorityDTO dto) {
        if(dto.isNew()) {
            return constructModel(dto);
        } else {
            return updateModel(dto);
        }
    }

    @Override
    public WebRoleAuthorityDTO toDTO(@NonNull final RoleAuthority model) {
        final WebRoleAuthorityDTO dto = new WebRoleAuthorityDTO();

        dto.setId(model.getId());

        this.convertCommonToDTO(model, dto);

        return dto;
    }

    /**
     * 构建新Model
     */
    private RoleAuthority constructModel(final WebRoleAuthorityDTO dto) {
        final RoleAuthority model = new RoleAuthority();
        this.dtoToModel(dto, model);
        return model;
    }

    /**
     * 更新Model
     */
    private RoleAuthority updateModel(final WebRoleAuthorityDTO dto) {
        final RoleAuthority model = this.roleAuthorityRepository.findById(dto.getId())
                .orElseThrow(() -> ExceptionHolder.serviceException(UaaErrorCode.E2001005002, RoleAuthority.class.getSimpleName()));
        this.dtoToModel(dto, model);
        return model;
    }

    private void dtoToModel(final WebRoleAuthorityDTO dto, final RoleAuthority model) {

    }
}
